package com.lyn.utils;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * http请求工具类
 * @author Lyn 2022/12/8
 * @version 1.0.0
 */
public class HttpUtil {
    public static String post(String url, JSONObject data) {
        return post(url, data.toString());
    }

    public static String post(String url, String data) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(data.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int length = 0;
                byte[] bytes = new byte[1024];
                while ((length = inputStream.read(bytes)) != -1) {
                    byteArrayOutputStream.write(bytes, 0, length);
                }
                byteArrayOutputStream.close();
                inputStream.close();
                return byteArrayOutputStream.toString();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * get 请求
     *
     * @param url url地址
     * @param par 参数
     * @return 请求结果
     */
    public static String get(String url, Map<String, String> par) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "keep-Alive");
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(getUrlPar(par).getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int length = 0;
                byte[] bytes = new byte[1024];
                while ((length = inputStream.read(bytes)) != -1) {
                    byteArrayOutputStream.write(bytes, 0, length);
                }
                byteArrayOutputStream.close();
                inputStream.close();
                return byteArrayOutputStream.toString();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析url带参为字符串
     *
     * @param par 参数map
     * @return url参数字符串
     */
    public static String getUrlPar(Map<String, String> par) {
        if (par == null || par.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (String key : par.keySet()) {
            if (i == 0) {
                sb.append("?").append(key).append("=").append(par.get(key));
            } else {
                sb.append("&").append(key).append("=").append(par.get(key));
            }
            i += 1;
        }
        return sb.toString();
    }
}
